<template>
  <div>
    <!--    面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--    卡片视图区-->
    <el-card>
      <!--      搜索,添加导航区-->
      <div style="margin-top: 15px;">
        <el-row :gutter='20'> <!--:gutter='20'表示每列相隔20 :span="8"表示这一列站8宽度-->
          <!--          搜索条-->
          <el-col :span="8">
            <!--            clearable使得可以清空，clear事件-->
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsers">
              <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
            </el-input>
          </el-col>
          <!--          添加用户框-->
          <el-col :span="4">
            <el-button @click="isShowAdd=true">添加用户</el-button>
          </el-col>

        </el-row>
      </div>
      <!--      展示区-->
      <div>
        <!--      用户表格：stripe隔行变色 prop代表这一项指定的数据项 :data="tableData"就是把里面的数据装到表格里面-->
        <el-table :data="tableData" stripe>
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <!--            这里重点注意：v-slot可以获取到插槽的props值，然而在element中，props值是一个叫row的对象-->
          <el-table-column label="状态" v-slot="slotProps">
            <!--              一个可以操控状态的开关，并且双向绑定-->
            <el-switch v-model="slotProps.row.mg_state" @change="userStateChanged(slotProps.row)"></el-switch>
          </el-table-column>
          <el-table-column label="操作" v-slot="slot">
            <!--              修改按钮-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(slot.row.id)"></el-button>
            <!--              删除按钮-->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(slot.row.id)"></el-button>
            <!--              分配角色按钮-->
            <!--              tooltip鼠标放上的消息提示，:enterable="false"鼠标不能进入消息提示框，content消息内容-->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="getRole(slot.row)"></el-button>
            </el-tooltip>
          </el-table-column>
        </el-table>
        <!--        页码条-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[4, 6, 8, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!--      对话框区-->
    <div>
      <!--添加用户-->
      <el-dialog title="添加用户" :visible.sync="isShowAdd" width="35%" @close="addDialogClosed">
        <!--              内容主体区域，model：数据绑定对象，rules：输入规则对象，prop：规则对应-->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!--              底部按钮区-->
        <span slot="footer" class="dialog-footer">
                <el-button @click="isShowAdd = false">取 消</el-button>
                <el-button type="primary" @click="adduser">确 定</el-button>
              </span>
      </el-dialog>
      <!--编辑用户-->
      <el-dialog title="修改信息" :visible.sync="isShowEdit" width="35%" @click="editDialogClosed">
        <!--        输入框区-->
        <el-form :model="editForm" ref="editFormRef" label-width="80px">
          <el-form-item label="用户名" prop="email">
            <el-input disabled :placeholder="editNow.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!--          底部按钮区-->
        <span slot="footer" class="dialog-footer">
            <el-button @click="isShowEdit = false">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
          </span>
      </el-dialog>
    <!--  分配角色-->
    <el-dialog title="分配角色" :visible.sync="isShowGetRole" width="500px">
      <el-form label-width="100px">
        <el-form-item label="当前用户">
          <el-input v-model="aRoel.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="选择角色">
          <el-select v-model="aRoel.rid">
            <el-option
                v-for="item in allRole"
                :label="item.roleName"
                :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="isShowEdit = false">取 消</el-button>
            <el-button type="primary" @click="addRole">确 定</el-button>
          </span>
    </el-dialog>
    </div>

  </div>
</template>

<script>
export default {
  name: "Users",
  data() {
    return {
      //修改表单的数据对象
      editForm: {
        username: '',
        email: '',
        mobile: '',
      },
      //修改表单的当前数据
      editNow: {},
      //添加表单的数据对象
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      //添加表单的数据规则对象
      addFormRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},//必选项；错误提示，失去焦点触发
          {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},//必选项；错误提示，失去焦点触发
          {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
        ],
        email: [
          {min: 9, max: 15, message: '长度在 9 到 15 个字符', trigger: 'blur'}
        ],
        mobile: [
          {min: 9, max: 15, message: '长度在 9 到 15 个字符', trigger: 'blur'}
        ]

      },
      //获取用户列表的参数对象
      queryInfo: {
        query: '',
        //当前的页码
        pagenum: 1,
        //当前每页可显示的数据
        pagesize: 4
      },
      //当前页面的用户数据
      tableData: [],
      //总共的数据
      total: 0,
      //所有角色【选择器用】
      allRole:[],
      //分配角色的用户
      aRoel:{
        name:'',
        id:0,
        rid:''
      },
      //是否隐藏添加用户的对话框
      isShowAdd: false,
      //是否隐藏编辑用户对话框
      isShowEdit: false,
      //分配角色对话框
      isShowGetRole:false
    }
  },

  methods: {
    getUsers() {
      this.$http.get('/users', {params: this.queryInfo}).then(res => {
        res = res.data
        this.tableData = res.data.users
        this.total = res.data.total
      })
    },
    //页面可展示数改变事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      //当数据发生了变化，就重新向服务器请求
      this.getUsers()
    },
    //页码值发生改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      //当数据发生了变化，就重新向服务器请求
      this.getUsers()
    },
    //监听开关状态的改变
    userStateChanged(a) {
      //注意这里传递参数的形式，不是params参数
      this.$http.put('users/' + a.id + '/state/' + a.mg_state).then(({data}) => {
        if (data.meta.status !== 200) {
          a.mg_state = !a.mg_state//因为更改失败了，使用要把我们显示的改回来
          return this.$message.error("更改错误")
        } else {
          return this.$message.success("更新成功")
        }
      })
    },
    //当添加的对话框关闭的时候
    addDialogClosed() {
      this.$refs.addFormRef.resetFields() //清空
    },
    //点击添加新用户
    adduser() {
      //先进行预校验
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        //校验成功时发起网络请求
        else {
          this.$http.post('/users', this.addForm).then(({data}) => {
            this.isShowAdd = false  //隐藏对话框
            this.$message.success("添加用户成功")
            this.getUsers()//刷新列表
          })
        }
      })
    },
    //点击编辑用户对话框
    edit(id) {
      this.isShowEdit = !this.isShowEdit
      this.$http.get('users/' + id).then(res => {
        const data = res.data
        if (data.meta.status != 200) {
          return this.$message.error('获取用户数据失败')
        } else {
          this.editNow = data.data
          console.log(this.editNow)
        }
      })
    },
    //点击完成编辑
    editUser() {
      this.isShowEdit = !this.isShowEdit
      this.$http.put('users/' + this.editNow.id, this.editForm).then(res => {
        const data = res.data
        if (data.meta.status !== 200) {
          return this.$message.error("更新失败")
        } else {
          this.$message.success('更新成功')
        }
      })
      this.getUsers()
    },
    //当编辑对话框关闭的时候
    editDialogClosed() {
      this.$refs.editFormRef.resetFields() //清空
    },
    //删除用户
    deleteUser(id) {
      this.$http.delete('users/' + id).then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error("删除失败")
        } else {
          this.$message.success("删除成功")
          this.getUsers()
        }
      })
    },
    //分配角色
    getRole(row){
      console.log('row')
      console.log(row)
      this.isShowGetRole=true
      this.$http.get('roles').then(res=>{
        if(res.data.meta.status!==200)return this.$message.error('获取角色失败')
        this.allRole=res.data.data
      })
      this.aRoel.id=row.id
      this.aRoel.name=row.username
    },
    //确认分配角色
    addRole(){
      this.$http.put('users/'+this.aRoel.id+'/role',this.aRoel).then(res=>{
        if(res.data.meta.status!==200)return this.$message.error('修改角色失败')
        this.$message.success('分配角色成功')
        this.aRoel.rid='' //还原
        console.log(this.aRoel)
        this.isShowGetRole=false
        this.getUsers()
      })
    }
  },

  created() {
    this.getUsers()
  },
}
</script>

<style scoped>

</style>